package net.keebook.webapp.ws;

import java.util.List;

import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

import net.keebook.webapp.dao.KeeBookDao;
import net.keebook.webapp.dao.PasswordDao;
import net.keebook.webapp.entity.KeeBook;
import net.keebook.webapp.entity.User;

import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


@Path("/{username}/getkeebook")
@Stateless
public class GetKeeBookService extends WebService {
	@Inject
	private PasswordDao passwordDao;
	@Inject
	private KeeBookDao keeBookDao;
	
	@GET
	@Produces(MediaType.APPLICATION_JSON)
	public String saveSettings(
			@PathParam("username") String username,
			@DefaultValue("") @QueryParam("password") String password)
	{	
		Logger.getLogger(this.getClass()).info("Incoming request");
		JSONObject result = new JSONObject();
		try {
			// Authentication
			User user = authenticate(username, password);
			if (user == null) {
				Logger.getLogger(this.getClass()).warn("Authentication failed for user " + username);
				result.put("authSuccess", false);
				result.put("success", false);
				return getResponse(result);
			}
			
			Logger.getLogger(this.getClass()).info("User " + username + " authenticated successfully (user id: "+user.getExposableId()+")");
			result.put("authSuccess", true);
			
			// Compile list of Kee Books
			List<KeeBook> keeBooks = getKeeBookDao().getList(user.getId());
			result.put("count", keeBooks.size());
			JSONArray resultList = new JSONArray();
			for (KeeBook keeBook : keeBooks) {
				JSONObject o = new JSONObject();
				o.put("id", keeBook.getExposableId());
				o.put("title", keeBook.getName());
				o.put("salt", keeBook.getSalt());
				resultList.put(o);
			}
			result.put("result", resultList);
			result.put("success", true);
		} catch (JSONException e) {
			return getResponse(ERROR_RESPONSE);
		}
		
		return getResponse(result);
	}

	public PasswordDao getPasswordDao() {
		return passwordDao;
	}

	public void setPasswordDao(PasswordDao passwordDao) {
		this.passwordDao = passwordDao;
	}

	public KeeBookDao getKeeBookDao() {
		return keeBookDao;
	}

	public void setKeeBookDao(KeeBookDao keeBookDao) {
		this.keeBookDao = keeBookDao;
	}
}
